<template>
    <topbar>
        首页
    </topbar>
    <div class="content">
        <div v-if="isShow">
            <el-card>

                <template #header>
                    <div class="card-header">
                        <span>今天的学习计划</span>
                        <el-button type="primary" @click="documentItem()">归档</el-button>
                    </div>
                </template>
                <p v-for="item,index in items" :key="index" class="item">
                    <el-checkbox  v-model="item.status" size="large" @change="isSelect()" :disabled="item.status">
                        <span :class="{strikethrough:item.status}">{{item.title}}</span>
                    </el-checkbox>
                    <div class="buttonStyle">
                         <el-button type="primary" icon="Edit" circle @click="modityItem(index)"/>
                        <el-button type="danger" icon="Delete" circle @click="deleteItem(index)"/>
                    </div>
                </p>
                <template #footer >
                    <div style="text-align: center;">
                        <span >计划创建时间:{{currentTime}}</span>
                    </div>
                    
                </template>
            </el-card>
            <el-progress :text-inside="true" :stroke-width="26" :percentage="itemPercentage" />
        </div>
        <el-empty description="今天还没有学习计划呢,快去添加学习计划吧!" v-if="!isShow" />
        <el-button class="plus" type="primary" icon="Plus" circle @click="status = true" />
        <el-dialog v-model="status" title="添加计划" width="500" align-center model>
            <el-form label-width="auto" style="max-width: 600px" :model="dataModel">
                <el-form-item label="任务名称">
                    <el-input v-model="dataModel.content" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="status = false">取消</el-button>
                    <el-button type="primary" @click="displayItems()">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {Plus,Delete} from '@element-plus/icons-vue'
import topbar from './topbar.vue';
import { onBeforeUpdate, onMounted, reactive, ref, toRaw } from 'vue';
import {Item,HistoryItem} from '../util/data.js'
import { ElNotification,ElMessage,ElMessageBox} from 'element-plus'
import { h } from 'vue'
let isShow = ref(false)
let dataModel = reactive({
    content:""
})
let currentTime = ref("")
let items = reactive([])
let status = ref(false)
let finishedNum = 0
let itemPercentage = ref(0)
function displayItems(){
    if (dataModel.content != "") {
        items.push(new Item(items.length + 1, dataModel.content))
        localStorage.setItem("data", JSON.stringify(toRaw(items)))
        dataModel.content = ""
        status.value = false
        isShow.value = true
        drawProgress()
        if (currentTime.value == "") {
            const date = new Date();
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            currentTime.value = `${year}-${month}-${day}`;
        }
        ElMessage({
            message: '添加成功',
            type: 'success',
        })
    } else {
        ElMessage({
            message: '计划名不能为空',
            type: 'warning',
        })
    }
   
}
function isNull(){
 if(items.length>0){
        isShow.value = true
        drawProgress()
    }else{
        isShow.value = false
        finishedNum = 0
    }
}
function modityItem(index){
    ElMessageBox.prompt('请修改名称', 'Tip', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputValue: items[index].title
  })
    .then(({ value }) => {
    items[index].title = value
    localStorage.removeItem("data")
    localStorage.setItem("data", JSON.stringify(toRaw(items)))
    console.log(items[index])
      ElMessage({
        type: 'success',
        message: "修改成功",
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '修改取消',
      })
    })
}
function deleteItem(index){
    ElMessageBox.confirm(
        '你确定要删除吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            items.splice(index, 1)
            isNull()
            drawProgress()
            localStorage.removeItem("data")
            localStorage.setItem("data", JSON.stringify(toRaw(items)))
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除取消',
            })
        })
    if(items[index].status){
         --finishedNum
    }
}
function isSelect(){
    ++finishedNum
    drawProgress()
    localStorage.removeItem("data")
    localStorage.setItem("data",JSON.stringify(toRaw(items)))

}
function drawProgress(){
   itemPercentage.value = Math.round(finishedNum/items.length*100)
   console.log(itemPercentage.value)
}
function documentItem(){
    if(items != null){
        let isExisting = localStorage.getItem("history")
        let previousItem = isExisting != null ? JSON.parse(isExisting) : []
        previousItem.push(new HistoryItem(currentTime.value, itemPercentage.value, ...toRaw(items)))
        console.log(previousItem)
        localStorage.setItem("history", JSON.stringify(previousItem))
        items = []
        localStorage.removeItem("data")
        isNull()
        ElNotification({
            title: '归档通知',
            message: h('i', { style: 'color: teal' }, '归档成功!'),
            type: 'success'
        })
    }else{
          ElNotification({
            title: '归档通知',
            message: h('i', { style: 'color: red' }, '归档失败!'),
            type: 'warning',
        })
    }
 
}
onMounted(()=>{
    if(localStorage.getItem("data")!=null){
        let array = JSON.parse(localStorage.getItem("data"))
        for(let i=0;i<array.length;i++){
            if(array[i].status){
                finishedNum++
            }
        }
        items.push(...array)
        console.log(items)
    }
    isNull()
})
</script>

<style scoped>
    .content{
        position: relative;
        height: 750px
    }
    .plus{
        position: absolute;
        bottom: 0;
        right: 0;
        font-size: 25px;
        width: 60px;
        height: 60px;
    }
    .item{
        display: flex;
        justify-content: space-between;
    }
    .strikethrough {
        text-decoration: line-through;
    }
    .card-header{
        display: flex;
        justify-content: space-between;
    }
    .card-header span{
        height: 32px;
        line-height: 32px;
    }
</style>